package plgdb

import (
	"dgo/MyProj/PrjDBUtils"
	"dgo/MyProj/PrjHttpUtils"
	"dgo/goutils/utils"
	"gitee.com/ymofen/supervalue"
	"net/http"
	"strings"
)

var (
	KEY_REQ_CNT    string = "reqcnt"
	KEY_PAGE_INDEX string = "page"
	KEY_PAGE_SIZE  string = "pagesize"
	KEY_POSI       string = "posi"
	KEY_POSI_NUM   string = "num"

	DEFAULT_LIST_KEYNAME string = "data"
	DEFAULT_PAGE_SIZE    int    = 20

	ERR_DB_ERR int = 504
)

const (
	VAR_NOT_EMPTY string = "$$NOTEMPTY$$"
)

type TGetParamValFunc func(key string) (bool, interface{})

type PlgDBRequest struct {
	PlgHttpRec
	TracesqlBuilder      utils.BytesBuilder
	OnGetParamValFunc    func(sender interface{}, key string) (bool, interface{})
	OnResConfig          func(orgconf *wrapper.SuperValue) (newconf *wrapper.SuperValue)
	BeforeUpdate         func(param *PlgDBUpdateParam) bool
	BeforeQryRequestFunc func(param *PlgDBQryParam) bool

	/**
	在响应之前回调,可以截获处理返回的数据
	*/
	OnDBBeforeResponseFunc func(sender *PlgDBRequest) bool
	AfterUpdate            func(param *PlgDBUpdateParam, uprec *PrjDBUtils.DaoUpdateRecord)
}

func (this *PlgDBRequest) GetURLString() string {
	if this.ReqR == nil {
		return ""
	}
	return this.ReqR.URL.String()
}

func (this *PlgDBRequest) GetUpData() *wrapper.SuperValue {
	// 提取url的参数
	upData := this.Req.ValueByName("data")
	if upData == nil {
		upData = this.Req
	}
	this.RangeURLParam(func(k, v string) bool {
		strs := strings.SplitN(k, ".", 2)
		if len(strs) == 2 && strs[0] == "data" {
			upData.SetKeyString(strs[1], v)
		}
		return true
	})
	return upData
}

func (this *PlgDBRequest) OnAfterExecSQL(tracesql int, sql string, err error, args ...interface{}) {
	if tracesql == 1 {
		this.TracesqlBuilder.AppendStr(sql)
		if len(args) > 0 {
			this.TracesqlBuilder.Appendf(", param:%v", args)
		}
		if err != nil {
			this.TracesqlBuilder.Appendf(", err:%s", err.Error())
		}
		this.TracesqlBuilder.AppendStr("\r\n")
	}
}

func (this *PlgDBRequest) DoResConfig(orgconf *wrapper.SuperValue) (newconf *wrapper.SuperValue) {
	if this.OnResConfig == nil {
		return orgconf
	} else {
		return this.OnResConfig(orgconf)
	}
}

func NewPlgDBRequest(w http.ResponseWriter, r *http.Request) *PlgDBRequest {
	rval := &PlgDBRequest{}
	rval.ReqR = r
	rval.RespW = w
	rval.Resp = wrapper.NewSVObject()
	rval.EncodeJSONEscape = true
	rval.Initial()

	if utils.DEBUG_MODE == 1 {
		rval.EncodeJSONEscape = false
	}

	if PrjHttpUtils.Config_DefaultAllowCrossAccess {
		PrjHttpUtils.AllowCrossAccessSet(w)
	}

	return rval
}
